package com.party.web.web.controller.activity;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.*;
import com.party.core.model.city.Area;
import com.party.core.model.city.City;
import com.party.core.model.commune.*;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.WithCount;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.*;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.notify.TargetTemplateType;
import com.party.core.model.order.OrderType;
import com.party.core.model.system.Dict;
import com.party.core.model.system.DictEnum;
import com.party.core.model.system.TargetType;
import com.party.core.model.user.User;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.activity.OrderActivityBizService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.commune.ICIntegralBizService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.count.IDataCountService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.gatherInfo.biz.GatherInfoMembersBizService;
import com.party.core.service.member.*;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.system.IDictService;
import com.party.core.service.system.ISysRoleService;
import com.party.core.service.thirdParty.IThirdPartyService;
import com.party.core.service.user.IUserService;
import com.party.web.biz.activity.ActivityBizService;
import com.party.web.biz.activity.MemberActBizService;
import com.party.web.biz.asynexport.IAsynExportService;
import com.party.web.biz.circle.CircleBizNewService;
import com.party.web.biz.crowdfund.ProjectBizService;
import com.party.web.biz.crowdfund.RepresentBizService;
import com.party.web.biz.crowdfund.TargetBizService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.gatherInfo.ItineraryBizService;
import com.party.web.biz.member.CIntegralBizToService;
import com.party.web.biz.member.CMomentBizService;
import com.party.web.biz.member.MemberMgmtService;
import com.party.web.biz.system.member.MemberBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.activity.ActivityOutput;
import com.party.web.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.web.web.dto.output.member.CMomentSave;
import com.party.web.web.security.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 活动
 *
 * @author Administrator
 */

@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/activity/activity")
public class ActivityController {

    @Value("#{party['mic.url']}")
    private String micUrl;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IActivityDetailService activityDetailService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IThirdPartyService thirdPartyService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private ICityService cityService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ActivityBizService activityBizService;

    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private RepresentBizService representBizService;

    @Autowired
    private IDataCountService dataCountService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    @Autowired
    private ActivityDetailBizService activityDetailBizService;

    @Autowired
    private CrowfundResourceBizService crowfundResourceBizService;

    @Autowired
    private CounterfoilBizService counterfoilBizService;

    @Autowired
    private CircleMemberBizService circleMemberBizService;

    @Autowired
    private CircleBizService circleBizService;

    @Autowired
    private OrderActivityBizService orderActivityBizService;

    @Autowired
    private ITargetTemplateService targetTemplateService;

    @Resource(name = "representAsynExportService")
    private IAsynExportService representAsynExportService;

    @Resource(name = "projectAsynExportService")
    private IAsynExportService projectAsynExportService;

    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private GatherInfoMembersBizService gatherInfoMembersBizService;
    @Autowired
    private IPackageCountService packageCountService;
    @Autowired
    private ITargetCopartnerService targetCopartnerService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private ItineraryBizService itineraryBizService;
    @Autowired
    private CircleBizNewService circleBizNewService;
    @Autowired
    private ISupportTransferService supportTransferService;
    @Autowired
    private TargetBizService targetBizService;
    @Autowired
    private ISupportService supportService;
    @Autowired
    private IEventGradationService eventGradationService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ICmemberBizService cmemberBizService;
    @Autowired
    private MemberActBizService memberActBizService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private ICIntegralTypeService integralTypeService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private CIntegralBizToService integralBizToService;
    @Autowired
    private ICIntegralBizService integralBizService;
    @Autowired
    private IMemberGroupPermissionService memberGroupPermissionService;
    @Autowired
    private MemberMgmtService memberMgmtService;
    @Autowired
    private CMomentBizService momentBizService;
    @Autowired
    private ICMemberInfoService cMemberInfoService;

    protected static Logger logger = LoggerFactory.getLogger(ActivityController.class);


    /**
     * 用于生成 那些活动中未生成直接付款的二维码
     *
     * @return
     */
    @RequestMapping(value = "createAllDirectPayQrCodeImg")
    public AjaxResult createAllDirectPayQrCodeImg() {
        AjaxResult result = new AjaxResult();
//        Page page = new Page();
//        page.setLimit(2);
        Activity activity = new Activity();
        activity.setStatus(0);//生成未截止的活动直接付款二维码
        List<Activity> activityList = activityService.listPage(activity, null);
        for (int i = 0; i < activityList.size(); i++) {
            String activityId = activityList.get(i).getId();
            String member = activityList.get(i).getMember();
            String filePath = fileBizService.getUploadCIPath(member, "zcActivity");
            String dpFileName = "directPay_" + activityId;
            String dpContent = "project/target_client_detail.html?id=" + activityId + "&dp=1";
            String imgUrl = fileBizService.uploadCloudOut
                    (dpFileName, filePath, dpContent, member);
            System.out.println("上传后的图片地址为：" + imgUrl);
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 跳转至发布 普通活动
     *
     * @param id
     * @return
     */
    @DataControl
    @RequestMapping(value = "publishAct")
    public ModelAndView publishAct(@ControlParam(table = "activity", column = "member", isRequired = false) String id) {
        ModelAndView mv = new ModelAndView("activity/publishAct");
        City city = new City();
        city.setIsOpen(1);
        mv.addObject("citys", cityService.list(city));
        Dict dict = new Dict();
        dict.setType(DictEnum.ACTIVITY_TYPE.getCode());
        mv.addObject("types", dictService.list(dict));

        CurrentUser newCurrentUser = RealmUtils.getNewCurrentUser();
        List<MemberGroup> memberGroups = new ArrayList<>();
        if (!newCurrentUser.isChild()) {
            memberGroups = memberGroupService.getChildList(newCurrentUser.getId());
        } else if (newCurrentUser.isXzgsAdmin()) {
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(newCurrentUser.getId(), null);
        }

        if (StringUtils.isNotEmpty(id)) {
            Activity activity = activityService.get(id);
            activity.setTitle(activity.getTitle().replace("\"", "“"));
            City myCity = cityService.get(activity.getCityId());
            if (myCity != null) {
                mv.addObject("cityName", myCity.getName());
            }
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            mv.addObject("activity", activity);
            mv.addObject("activityDetail", activityDetail);

            Counterfoil t = new Counterfoil();
            t.setBusinessId(id);
            List<Counterfoil> counterfoils = counterfoilService.list(t);
            mv.addObject("counterfoils", counterfoils);

            Map<String, Object> resultMap = gatherProjectBizService.getProjectBiz(activity.getId());
            mv.addAllObjects(resultMap);
        }
        mv.addObject("childrens", memberGroups);
        Map<Integer, String> counterTypes = CounterfoilType.convertMap();
        mv.addObject("counterTypes", counterTypes);
        mv.addObject("isGoods", false);
//		String currentDate = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
//		mv.addObject("currentDate", currentDate);
        return mv;
    }

    /**
     * 跳转至发布 众筹活动
     *
     * @param id
     * @return
     */
    @DataControl
    @RequestMapping(value = "publishZcAct")
    public ModelAndView publishZcAct(@ControlParam(table = "activity", column = "member", isRequired = false) String id) {
        ModelAndView mv = new ModelAndView("activity/publishZcActNew");
        if (StringUtils.isNotEmpty(id)) {
            /** 活动 **/
            Activity activity = activityService.get(id);
            ActivityOutput activityOutput = ActivityOutput.transform(activity);
            activityOutput.setEditShare(activity.getEditShare());
            String address = activityService.getShowAddress(activity);
            mv.addObject("address", address);
            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
            mv.addObject("picList", picList);
            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(activity.getId(), "2");
            if (videoList.size() > 0) {
                mv.addObject("video", videoList.get(0));
            }
            mv.addObject("activity", activityOutput);

            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            mv.addObject("activityDetail", activityDetail);


            ThirdMember thirdMember = thirdMemberService.findByTargetId(activity.getId());
            mv.addObject("thirdMember", thirdMember);

            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            mv.addObject("crowdfundEvent", crowdfundEvent);

            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
            mv.addObject("counterfoils", counterfoils);
        } else {
            CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
            crowdfundEvent.setProgress(YesNoStatus.YES.getCode()); // 进行中
            crowdfundEvent.setCreateBy(RealmUtils.getCurrentUser().getId());
            crowdfundEvent.setCheckStatus(1);//审核通过的主题才能显示出来
            List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.list(crowdfundEvent);
            mv.addObject("crowdfundEventList", crowdfundEventList);
        }
        return mv;
    }

    /**
     * 跳转至详情 普通活动
     *
     * @param actId
     * @return
     */
    @DataControl
    @RequestMapping(value = "activityDetail")
    public ModelAndView activityDetail(@ControlParam(table = "activity", column = "member") String actId) {
        ModelAndView mv = new ModelAndView("activity/activityDetail");
        ActivityDetail activityDetail = activityDetailService.getByRefId(actId);
        if (activityDetail != null) {
            activityDetailBizService.castToHTML(activityDetail);
        }
        // 获取票价
        String newPrice = counterfoilBizService.getShowPrice(null, actId);
        mv.addObject("newPrice", newPrice);
        Activity activity = activityService.get(actId);
        //DataCount dataCount = dataCountService.findByTargetId(actId);
        //mv.addObject("count", dataCount);
        mv.addObject("activity", activity);
        mv.addObject("activityDetail", activityDetail);
        return mv;
    }

    /**
     * 跳转至详情 众筹活动
     *
     * @param actId
     * @return
     */
    @DataControl
    @RequestMapping(value = "zcActivityDetail")
    public ModelAndView zcActivityDetail(@ControlParam(table = "activity", column = "member") String actId) {
        ModelAndView mv = new ModelAndView("activity/zcActivityDetail");
        Activity activity = activityService.get(actId);
        mv.addObject("activity", activity);
        ActivityDetail activityDetail = activityDetailService.getByRefId(actId);
        if (activityDetail != null) {
            activityDetailBizService.castToHTML(activityDetail);
        }

        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
        if (null != crowdfundEvent) {
            List<EventGradation> eventGradations = eventGradationService.withCityNameByEventId(crowdfundEvent.getId());
            mv.addObject("eventGradations", eventGradations);
        }

        // 众筹金额
        Double actualAmount = projectService.getTotalAmountForTargetId(actId);

        //浏览量
        Integer viewNum = activityService.crowdfundView(actId);
        String address = activityService.getShowAddress(activity);
        mv.addObject("actualAmount", actualAmount);
        mv.addObject("activityDetail", activityDetail);
        mv.addObject("viewNum", viewNum);
        mv.addObject("crowdfundEvent", crowdfundEvent);
        mv.addObject("address", address);
        return mv;
    }

    /**
     * 众筹列表
     *
     * @param id                活动编号
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 输出视图
     */
    @DataControl
    @RequestMapping(value = "zcCrowdfundList")
    public ModelAndView crowdfundList(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor, Page page) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("activity/zcCrowdfund");

        projectWithAuthor.setTargetId(id);
        projectWithAuthor.setPayType(0);

        Integer isSuccess = projectWithAuthor.getIsSuccess();

        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page, RealmUtils.getCurrentUser().getId());

        projectWithAuthor.setIsSuccess(isSuccess);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);
        modelAndView.addObject("crowdfundNum", page.getTotalCount());
        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);

        modelAndView.addAllObjects(targetBizService.getTargetData(id));
        modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "crowdfund" + id));
        return modelAndView;
    }


    /**
     * 直接众筹列表
     *
     * @param id                活动编号
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 输出视图
     */
    @DataControl
    @RequestMapping(value = "zcDirectPayList")
    public ModelAndView zcDirectPayList(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor, Page page) {
        page.setLimit(20);

        ModelAndView modelAndView = new ModelAndView("activity/zcDirectPayList");

        Integer isSuccess = projectWithAuthor.getIsSuccess();//先保存查询类型

        if (null != projectWithAuthor.getIsSuccess() && 0 == projectWithAuthor.getIsSuccess()) { // 众筹中
            projectWithAuthor.setIsSuccess(10);
        }

        projectWithAuthor.setPayType(1);
        projectWithAuthor.setTargetId(id);
        List<ProjectForActivityOutput> dpProjectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, page, RealmUtils.getCurrentUser().getId());
        dpProjectForActivityOutputList.stream().forEach(directPay -> {
            SupportWithMember supportWithMember = new SupportWithMember();
            supportWithMember.setProjectId(directPay.getId());
            List<SupportWithMember> tempList = supportService.findByProjectId(directPay.getId());
            if (tempList != null && tempList.size() > 0) {
                Support support = tempList.get(0);
                directPay.setSupportId(support.getId());
            }
            String filePath = fileBizService.getUploadCIPath("directPay", directPay.getAuthorId());
            String dpCodeUrl = cosBizService.getPreviewPictureUrl(filePath + directPay.getId());
            directPay.setQrCodeUrl(dpCodeUrl);//直接付款众筹详情二维码
            directPay.setUrl(projectBizService.getDirectPayUrl(directPay.getId()));//查看链接
        });

        projectWithAuthor.setIsSuccess(isSuccess);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);
        modelAndView.addObject("list", dpProjectForActivityOutputList);
        modelAndView.addObject("page", page);
        modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "zczjfk_crowdfund" + id));
        modelAndView.addAllObjects(targetBizService.getTargetData(id));
        return modelAndView;
    }


    /**
     * 导出众筹列表
     *
     * @param id 目标编号
     * @return
     */
    @DataControl
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "crowdfundListExport")
    public AjaxResult crowdfundListExport(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor,
                                          HttpServletRequest request) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                projectAsynExportService.export(id, projectWithAuthor, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * 导出转入列表
     *
     * @param id 目标编号
     * @return
     */
    @DataControl
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-转入列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "zcShiftToPeopleListExport")
    public AjaxResult zcShiftToPeopleListExport(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor,
                                                HttpServletRequest request) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                projectAsynExportService.exportTransferData(id, projectWithAuthor, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }


    @DataControl
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-直接付款列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "directPayListExport")
    public AjaxResult directPayListExport(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor, HttpServletRequest request) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                projectAsynExportService.exportDPData(id, projectWithAuthor, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * 联合发起列表
     *
     * @param id   活动编号
     * @param page 分页参数
     * @return 输出视图
     */
    @DataControl
    @RequestMapping(value = "zcRepresentList")
    public ModelAndView representList(@ControlParam(table = "activity", column = "member") String id, WithCount withCount, Page page) {
        ModelAndView modelAndView = new ModelAndView("activity/zcRepresent");
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(representBizService.listForActivityCommon(page, withCount, id));
        return modelAndView;
    }

    /**
     * 联合发起列表导出
     *
     * @param id 活动编号
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "representListExport")
    public AjaxResult representListExport(@ControlParam(table = "activity", column = "member") String id, WithCount withCount,
                                          HttpServletRequest request) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                representAsynExportService.export(id, withCount, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * 活动列表
     *
     * @param activity
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "activityList")
    public ModelAndView activityList(ActivityWithMemberPartner activity, Page page, CommonInput commonInput) {
        if (null == commonInput.getTimeStatus()) {
            commonInput.setTimeStatus(YesNoStatus.NO.getCode());
        }
        ModelAndView mv = new ModelAndView("activity/publishList");

        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(0);
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        CurrentUser user = RealmUtils.getNewCurrentUser();
        List<MemberGroup> memberGroupList = new ArrayList<>();
        boolean isSearchData = true;
        MemberGroup memberGroup = memberGroupService.get(user.getId());
        if (!Constant.MEMBER_XZGSADMIN.equals(memberGroup.getType())) {
            if (user.isTwoLevelChildren()) { // 二级账号
                List<String> targetIds = Lists.newArrayList();
                Integer isShowAll = memberGroupPermissionService.getIsShowAll(TargetType.ACTIVITY.getCode(), user.getId(), user.getPartnerId(), targetIds);
                if (null != isShowAll) {
                    if (YesNoStatus.YES.getCode().equals(isShowAll)) {
                        activity.setMember(user.getPartnerId());
                    } else {
                        params.put("ids", targetIds);
                    }
                } else {
                    isSearchData = false;
                }
            } else if (!user.isChild()) { // 主账号
                memberGroupList = memberGroupService.getChildWithMyAndName(user.getId());
                List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
                params.put("orgIds", orgIds);
            } else if (user.isOneLevelChildren()) { // 一级账号
                activity.setMember(user.getId());
            }
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(user.getId(), user.getPartnerId());
        }
        List<ActivityWithMemberPartner> activities = Lists.newArrayList();
        if (isSearchData) {
            activities = activityService.webListPage(activity, params, page);
        }

        mv.addObject("input", commonInput);

        List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "activity");
            Map<String, String> qrCodeMap = new HashMap<String, String>();
            ActivityOutput output = ActivityOutput.transform(input);
            output.setCreateBy(input.getMemberId());
            // 报名人数
            List<Counterfoil> counterfoils = counterfoilBizService.getActivityCounterfoils(input.getId());
            Activity dbActivity = activityService.get(input.getId());
            if (counterfoils.size() > 0) {
                String newPrice = counterfoilBizService.getShowPrice(counterfoils, input.getId());
                output.setNewPrice(newPrice);
            } else {
                dbActivity = orderActivityBizService.updateActivityInfo(input.getId());
            }
            output.setJoinNum(dbActivity.getJoinNum());
            output.setLimitNum(dbActivity.getLimitNum());

            // 活动二维码
            String detailFileName = "detail_" + input.getId();
            String content = "hd/hd_detail.html?hdId=" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            qrCodeMap.put("detailQrCode", qrCodeUrl);
            qrCodeMap.put("detailQrCodeContent", micUrl + content);

            // 签到二维码
            String signFileName = "sign_" + input.getId();
            String signQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + signFileName);
            qrCodeMap.put("signQrCode", signQrCodeUrl);

            // 分销二维码
/*			String fxFileName = "fx_" + input.getId();
			String disContent = activityBizService.getDistributionUrl(input.getId(), input.getMemberId());
			String fxQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fxFileName);
			qrCodeMap.put("disQrCode", fxQrCodeUrl);
			qrCodeMap.put("disQrCodeContent", micUrl + disContent);*/

            output.setQrCodeMap(qrCodeMap);
            return output;
        });

        //是否拥有行知公社权限
        boolean isCommune = integralBizToService.isXZGSJurisdiction(user.getId());
        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("isCommune", isCommune);
        mv.addObject("activities", activityOutputs);
        mv.addObject("page", page);
        mv.addObject("activity", activity);
        mv.addObject("isChild", user.isChild());
        mv.addObject("isTwoLevelChildren", user.isTwoLevelChildren());
        mv.addObject("isXzgsAdmin", user.isXzgsAdmin());
        return mv;
    }

    /**
     * 众筹项目列表
     *
     * @param activity
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "zcActivityList")
    public ModelAndView zcActivityList(ActivityWithMemberPartner activity, Page page, CommonInput commonInput,
                                       String eventName, Integer isMultiple) {
        ModelAndView mv = new ModelAndView("activity/publishZcActivityList");
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(1);

        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<String> orgIds = memberGroupService.getChildWithMy(RealmUtils.getCurrentUser().getId());
        params.put("orgIds", orgIds);

        params.put("eventName", eventName);
        params.put("isMultiple", isMultiple);
        List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);

        List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "zcActivity");
            Map<String, String> qrCodeMap = new HashMap<String, String>();
            ActivityOutput output = ActivityOutput.transform(input);

            Double actualAmount = projectService.getTotalAmountForTargetId(input.getId());
            output.setTotalMoney(actualAmount);

            Integer isMultipleNew = input.getIsMultiple();

            // 众筹联合发起二维码
            String dyFileName = "dy_" + input.getId();
            String content = "project/target_detail.html?id=" + input.getId();
            if (YesNoStatus.YES.getCode().equals(isMultipleNew)) {
                content = "project/target_sponsor_multi.html?id=" + input.getId();
            }
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + dyFileName);
            qrCodeMap.put("dyQrCode", qrCodeUrl);
            qrCodeMap.put("dyQrCodeContent", micUrl + content);

            // 众筹项目详情二维码
            String detailFileName = "detail_" + input.getId();
            String detailContent = "project/target_client_detail.html?id=" + input.getId();
            if (YesNoStatus.YES.getCode().equals(isMultipleNew)) {
                detailContent = "project/target_multi_detail.html?id=" + input.getId();
            }
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            qrCodeMap.put("detailQrCode", detailQrCodeUrl);
            qrCodeMap.put("detailQrCodeContent", micUrl + detailContent);

            if (YesNoStatus.NO.getCode().equals(isMultipleNew)) {
                Activity addressActivity = new Activity();
                addressActivity.setCityId(input.getCityId());
                addressActivity.setArea(input.getArea());
                addressActivity.setPlace(input.getPlace());
                String address = activityService.getShowAddress(addressActivity);
                output.setPlace(address);

                // 直接众筹项目详情二维码
                String dpDetailFileName = "directPay_" + input.getId();
                String dpDetailContent = "project/target_client_detail.html?id=" + input.getId();
                String dpDetailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + dpDetailFileName);
                qrCodeMap.put("dpDetailQrCode", dpDetailQrCodeUrl);
                qrCodeMap.put("dpDetailQrCodeContent", micUrl + dpDetailContent);
            }
            output.setQrCodeMap(qrCodeMap);
            return output;
        });
        mv.addObject("activities", activityOutputs);
        mv.addObject("page", page);
        mv.addObject("eventName", eventName);
        mv.addObject("isMultiple", isMultiple);
        mv.addObject("input", commonInput);
        mv.addObject("activity", activity);
        return mv;
    }

    /**
     * 发布保存
     *
     * @param startDate
     * @param endDate
     * @param activity
     * @param activityDetail
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = {"save"})
    public AjaxResult save(String startDate, String endDate, String areaSelect, String areaInput, String isFree, Activity activity,
                           ActivityDetail activityDetail, BindingResult result, GatherProject gatherProject, String childrenId) {
        try {
            String memberId = RealmUtils.getCurrentUser().getId();
            //没有选择分社时的默认分社
            if (StringUtils.isNotEmpty(childrenId)) {
                memberId = childrenId;
            } else if (Constant.MEMBER_XZGSADMIN.equals(RealmUtils.getCurrentUser().getType())) {
                memberId = RealmUtils.getNewCurrentUser().getPartnerId();
            }

            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            if (StringUtils.isNotEmpty(isFree) && isFree.equals("free")) {
                activity.setPrice(new Float(0.0));
            }
            if (StringUtils.isNotEmpty(startDate)) {
                activity.setStartTime(DateUtils.parse(startDate, "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isNotEmpty(endDate)) {
                activity.setEndTime(DateUtils.parse(endDate, "yyyy-MM-dd HH:mm"));
            }
            activity.setTitle(activity.getTitle().replace("\"", "“"));
            User user = userService.findByLoginName("admin");
            if (StringUtils.isNotEmpty(areaInput)) {
                activity.setArea(areaInput);
            }
            if (StringUtils.isNotEmpty(areaSelect)) {
                activity.setArea(areaSelect);
            }
            activity.setThirdPartyId("a287a2a4e8e94fe6bd5fb19cad345da6");// 活动供应商默认是同行者


            if (StringUtils.isNotEmpty(activity.getId())) {

                MemberAct memberAct = new MemberAct();
                memberAct.setActId(activity.getId());
                List<MemberAct> memberActs = memberActService.listPage(memberAct, null);
                if (memberActs.size() > 0 && !activity.getMember().equals(memberId)) {
                    throw new BusinessException("活动下有报名人员，不能修改活动发布者!");
                }

                // 更新内容
                Activity t = activityService.get(activity.getId());// 从数据库取出记录的值
                MyBeanUtils.copyBeanNotNull2Bean(activity, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                //当前活动没有报名者时，可以修改活动发布者
                t.setMember(memberId);
                activityService.update(t);// 保存

                memberId = t.getMember();
            } else {// 新增表单保存
                activity.setIsCopartner(2); // 不是合伙人
                activity.setIsOpen(1); // 报名开启
                activity.setShareNum(0); // 分享数
                activity.setReadNum(0); // 阅读数
                activity.setJoinNum(0); // 报名数
                activity.setGoodNum(0); // 点赞数
                activity.setCreateBy(user.getId());
                activity.setUpdateBy(user.getId());
                activity.setMember(memberId); // 当前用户
                activity.setCheckStatus("1"); // 默认审核成功
                activity.setMicWebStatus(1); // 微网站效果
                activity.setInviteOnly(0); // 是否持邀请码参与
                activity.setIsAllowedOutside(0); // 是否允许在其它城市频道显示
                activity.setShowFront(0); // 不显示在前端
                activityService.insert(activity);// 保存
                try {
                    CMomentSave cMomentSave = new CMomentSave();
                    cMomentSave.setPartnerId(activity.getMember());
                    cMomentSave.setBizId(activity.getId());
                    cMomentSave.setActivity(activity);
                    cMomentSave.setMomentType(MomentType.ACTIVITY_PUBLISH.getCode());
                    momentBizService.businessSaveCMoment(cMomentSave);
                } catch (Exception e) {
                    logger.error("发布活动同时发布动态--失败");
                }
            }

            /************* 详情 ****************/
            activityDetailBizService.saveBiz(activity.getId(), activityDetail);
            counterfoilBizService.saveBiz(activity.getCounterfoils(), activity.getId(), Constant.BUSINESS_TYPE_ACTIVITY, memberId);
            gatherProject.setType(GatherProject.TYPE_ACT);
            gatherProject.setTargetId(activity.getId());
            gatherProject.setCreateBy(user.getId());
            gatherProject.setUpdateBy(user.getId());
            gatherProject.setTitle(activity.getTitle() + "的报名信息收集");
            gatherProject.setPicture(activity.getPic());
            gatherProject.setContent(null);
            gatherProject.setId(null);
            gatherProjectBizService.saveProjectBiz(gatherProject);

            activityBizService.uploadQrCode(memberId, activity.getId());


            return AjaxResult.success("活动、众筹保存成功", activity.getId());
        } catch (BusinessException e) {
            logger.error("活动下有报名人员，不能修改活动发布者");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("活动、众筹保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 获取城市
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getCitys")
    public List<City> getCitys() {
        City city = new City();
        city.setIsOpen(1);
        List<City> citys = cityService.list(city);
        return citys;
    }

    /**
     * 前端城市三级联动
     *
     * @param cityName
     * @return
     */
    @ResponseBody
    @RequestMapping("getAreaByCityName")
    public List<Area> getAreaByCityName(String cityName) {
        List<Area> areas = areaService.getAreaByCityName(cityName);
        return areas;
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @DataControl
    @ResponseBody
    @UserOperate(moduleName = "活动/众筹项目", behaviorType = BehaviorType.DELETE)
    @RequestMapping(value = "deleteLogic")
    public AjaxResult deleteLogic(@ControlParam(table = "activity", column = "member") String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return new AjaxResult(false);
            }

            MemberAct t = new MemberAct();
            t.setActId(id);
            List<MemberAct> memberActs = memberActService.list(t);
            // 没有人报名可以直接删除
            if (memberActs.size() == 0) {
//				TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(id);
//				if (targetCopartner != null) {
//					return new AjaxResult(false, "已分配合伙人，不能删除");
//				}
                Activity activity = activityService.get(id);
                activity.setDelFlag(BaseModel.DEL_FLAG_DELETE);
                activityService.update(activity);
            } else {
                return new AjaxResult(false, "已有人报名，不能删除");
            }

            return new AjaxResult(true);
        } catch (Exception e) {
            logger.error("活动删除异常", e);
        }
        return new AjaxResult(false);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "delete")
    public AjaxResult delete(@ControlParam(table = "activity", column = "member") String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return new AjaxResult(false);
            }

            Activity activity = activityService.get(id);
            // 没有人报名可以直接删除
            if (activity.getJoinNum() == 0) {
                MemberAct t = new MemberAct();
                t.setActId(id);
                List<MemberAct> memberActs = memberActService.list(t);
                for (MemberAct memberAct : memberActs) {
                    if (memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_CANCEL.getCode())
                            || memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode())
                            || memberAct.getCheckStatus().equals(ActStatus.ACT_STATUS_NO_JOIN.getCode())) {
                        counterfoilBusinessService.deleteByBusinessId(memberAct.getId());
                        memberActService.delete(memberAct.getId());
                    }
                }
                activityDetailService.deleteByRefId(id);
                activityService.delete(id);
                return new AjaxResult(true);
            } else {
                return new AjaxResult(false, "已有人报名不能删除");
            }

        } catch (Exception e) {
            logger.error("活动删除异常", e);
        }
        return new AjaxResult(false);
    }

    /**
     * 删除资源图片
     *
     * @param resourceId 资源ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delZcActivityPic")
    public AjaxResult delZcActivityPic(String resourceId) {
        crowfundResourcesService.delete(resourceId);
        return AjaxResult.success();
    }

    /**
     * 创建业务圈子
     *
     * @param actId
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "createCircle")
    public AjaxResult createCircle(@ControlParam(table = "activity", column = "member") String actId, String type) {
        try {
            Activity activity = activityService.get(actId);
            MemberAct memberAct = new MemberAct();
            memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            memberAct.setActId(actId);
            List<MemberAct> memberActs = new ArrayList<MemberAct>();
            if (type.equals("1")) { // 已成功
                memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
                memberActs = memberActService.list(memberAct);
            } else if (type.equals("2")) {
                if (activity.getIsCrowdfunded() == 0) {
                    memberActs = memberActService.list(memberAct); // 全部
                } else if (activity.getIsCrowdfunded() == 1) {
                    Set<Integer> status = new HashSet<Integer>();
                    // status.add(ActStatus.ACT_STATUS_CANCEL.getCode());
                    // status.add(ActStatus.ACT_STATUS_NO_JOIN.getCode());
                    memberActs = memberActService.getSuccessMemberAct(memberAct, status);
                }
            }

            List<String> memberIds = new ArrayList<String>();
            memberIds.add(activity.getMember());

            String remarks = activity.getTitle() + "——";
            if (activity.getIsCrowdfunded() == 0) {
                remarks += (type.equals("1") ? "已报名成功人员圈子" : "全部报名人员圈子");
            } else if (activity.getIsCrowdfunded() == 1) {
                remarks += (type.equals("1") ? "已众筹成功人员圈子" : "全部发起众筹人员圈子");
            }
            remarks = remarks.replace("\"", "“");
            activity.setRemarks(remarks);

            String circleId = circleBizService.createCircleBusiness(actId, activity, type);
            circleMemberBizService.circleMemberManage(memberActs, circleId, type, memberIds, activity.getMember());

            circleBizNewService.uploadQrCode(activity.getMember(), circleId);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成圈子异常", e);
            return AjaxResult.error("生成圈子异常");
        }
    }

    /**
     * 消息发送视图
     *
     * @param targetId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "messageView")
    public ModelAndView messageView(String targetId, Integer type, String id, String behavior) {
        String memberId = RealmUtils.getCurrentUser().getId();
        ModelAndView modelAndView = new ModelAndView("/activity/messageView");
        TargetTemplate targetTemplate = null;

        if ("add".equals(behavior)) {
            targetTemplate = targetTemplateService.recently(targetId, type);
            if (null == targetTemplate) {
                targetTemplate = new TargetTemplate();
                targetTemplate.setTargetId(targetId);
                targetTemplate.setType(type);
            }
        } else {
            targetTemplate = targetTemplateService.get(id);
        }
        Map<Integer, String> types = TargetTemplateType.convertMap(1);
        for (Map.Entry<Integer, String> entry : types.entrySet()) {
            Integer status;
            if (TargetTemplateType.ACT_STATUS_ALL.getCode().equals(entry.getKey())) {
                status = null;
            } else {
                status = entry.getKey() - 4;
            }
            Integer num = memberActService.countByActivity(targetId, status);
            entry.setValue(entry.getValue() + "(" + num + "人)");
        }
        PackageCount packageCount = packageCountService.getUnique(new PackageCount(memberId, TargetType.PUSH_SMS.getCode()));
        modelAndView.addObject("packageCount", packageCount);
        modelAndView.addObject("types", types);
        modelAndView.addObject("behavior", behavior);
        modelAndView.addObject("targetTemplate", targetTemplate);
        return modelAndView;
    }

    /**
     * 保存模板同时消息推送
     *
     * @param targetTemplate 目标模板
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "sendAndSave")
    public AjaxResult send(TargetTemplate targetTemplate) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            boolean isCanFlag = activityBizService.sendAndSave(targetTemplate);
            if (!isCanFlag) {
                return AjaxResult.error("短信剩余数量不足，请先充值");
            }
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            logger.error("消息推送异常", be);
            return ajaxResult;
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("发送异常");
            logger.error("消息推送异常", e);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 消息推送-定时-活动
     *
     * @param targetTemplate
     * @param sendTimeString: 格式为yyyy-MM-dd HH:mm:ss
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendQuartzForActivity")
    public AjaxResult sendQuartzForActivity(TargetTemplate targetTemplate, String sendTimeString, String behavior) {
        try {
            return activityBizService.sendQuartz(targetTemplate, sendTimeString, behavior, Constant.SEND_SHORT_MESSAGE_TYPE_ACTIVITY);
        } catch (Exception e) {
            logger.error("定时短信推送异常", e);
            return AjaxResult.error("定时短信推送异常");
        }
    }

    /**
     * 删除短信
     *
     * @param id: 模板id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delQuartzForActivity")
    public AjaxResult delQuartzForActivity(String id) {
        try {
            return activityBizService.delQuartzForActivity(id);
        } catch (Exception e) {
            logger.error("删除定时短信异常", e);
            return AjaxResult.error("定时短信删除异常");
        }
    }

    /**
     * 消息推送
     *
     * @param id 目标模板id
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "send")
    public AjaxResult send(String id) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            boolean isCanFlag = activityBizService.send(id);
            if (!isCanFlag) {
                return AjaxResult.error("短信剩余数量不足，请先充值");
            }
        } catch (BusinessException be) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            logger.error("消息推送异常", be);
            return ajaxResult;
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("发送异常");
            logger.error("消息推送异常", e);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 创建业务ID
     *
     * @param actId
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "createGatherInfo")
    public AjaxResult createGatherInfo(@ControlParam(table = "activity", column = "member") String actId, String type) {
        try {
            MemberAct memberAct = new MemberAct();
            memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            memberAct.setActId(actId);
            if (type.equals("1")) { // 已成功
                memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
            }
            List<MemberAct> memberActs = memberActService.list(memberAct); // 全部

            Activity activity = activityService.get(actId);
            String remarks = activity.getTitle() + "——" + (type.equals("1") ? "报名成功人员信息收集项目" : "全部报名人员信息收集项目");
            remarks = remarks.replace("\"", "“");
            activity.setRemarks(remarks);

            String projectId = gatherInfoMembersBizService.createGatherInfoProjectBusiness(actId, activity, type, activity.getMember());
            gatherInfoMembersBizService.addMember(projectId, memberActs, activity.getMember());

            itineraryBizService.uploadQrCode(activity.getMember(), projectId);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成人员信息收集项目异常", e);
            return AjaxResult.error("生成人员信息收集项目异常");
        }
    }

    /**
     * 众筹项目主页扫码预览
     *
     * @param activityId 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("getDetailQrCode")
    public AjaxResult getDetailQrCode(String activityId) {
        if (StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("项目id不能为空");
        }
        try {
            Activity activity = activityService.get(activityId);
            String memberId = activity.getMember();
            /*** 众筹项目详情二维码 ***/
            String filePath = fileBizService.getUploadCIPath(memberId, "zcActivity");
            String xqFileName = "detail_" + activityId;
            String detailContent = "project/target_client_detail.html?id=" + activityId;
            String previewUrl = fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, memberId);
            return AjaxResult.success((Object) previewUrl);
        } catch (Exception e) {
            return AjaxResult.error("获取二维码异常");
        }
    }

    /**
     * 转入的人列表
     *
     * @param id                活动编号
     * @param projectWithAuthor 众筹信息
     * @param page              分页参数
     * @return 输出视图
     */
    @DataControl
    @RequestMapping(value = "zcShiftToPeopleList")
    public ModelAndView zcShiftToPeopleList(@ControlParam(table = "activity", column = "member") String id, ProjectWithAuthor projectWithAuthor, Page page) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("activity/zcShiftToPeople");

        projectWithAuthor.setTargetId(id);
        projectWithAuthor.setTransferP(true);
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectTransferForActivityList(projectWithAuthor, page, RealmUtils.getCurrentUser().getId());

        modelAndView.addObject("list", projectForActivityOutputList);
        modelAndView.addObject("page", page);

        modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + "zczr_crowdfund" + id));
        modelAndView.addAllObjects(targetBizService.getTargetData(id));
        return modelAndView;
    }


    /**
     * 跳转至详情 众筹活动
     *
     * @param actId
     * @return
     */
    @DataControl
    @RequestMapping(value = "memberActView")
    public ModelAndView memberActInfo(String actId) {
        ModelAndView mv = new ModelAndView("activity/memberActView");

        mv.addObject("actId", actId);

        List<Counterfoil> counterfoils = counterfoilBizService.getActivityCounterfoils(actId);
        mv.addObject("counterfoils", counterfoils);

        //一级行业列表
        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);
        return mv;
    }

    /**
     * 活动自动报名
     *
     * @param applyInput 报名输入视图
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "autoApply")
    public AjaxResult autoApply(@Validated ApplyInput applyInput, BindingResult result, HttpServletRequest request, GatherProject project) {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }
            if (StringUtils.isEmpty(applyInput.getCounterfoilId())) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "没有票据ID");
            }
            if (StringUtils.isNotEmpty(applyInput.getMemberId())) {
                MemberAct memberAct = new MemberAct();
                memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                memberAct.setActId(applyInput.getId());
                memberAct.setCheckStatus(ActStatus.ACT_STATUS_PAID.getCode());
                memberAct.setMemberId(applyInput.getMemberId());
                List<MemberAct> memberActs = memberActService.list(memberAct);
                if (memberActs.size() > 0) {
                    throw new BusinessException(90000, "该用户已经报过名了");
                }


                //查询是否还有待支付报名用户
                MemberAct memberActToBePay = new MemberAct();
                memberActToBePay.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                memberActToBePay.setActId(applyInput.getId());
                memberActToBePay.setCheckStatus(ActStatus.ACT_STATUS_AUDIT_PASS.getCode());
                memberActToBePay.setMemberId(applyInput.getMemberId());
                List<MemberAct> memberActsToBePay = memberActService.list(memberActToBePay);
                if (memberActsToBePay.size() > 0) {
                    throw new BusinessException(90000, "该用户已经报过名了,请尽快去支付！");
                }
            }

            Counterfoil counterfoil = counterfoilService.get(applyInput.getCounterfoilId());
            if (null == counterfoil) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "票据不存在");
            } else {
                //票种数量
                int limitNumDb = counterfoil.getLimitNum();
                //已购数量
                int joinNumDb = counterfoil.getJoinNum();
                if (limitNumDb == joinNumDb) {
                    throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "该票种已卖完");
                }
            }
            Member cmember = null;
            Activity activity = activityService.get(applyInput.getId());
            String partnerId = activity.getMember();
            if (StringUtils.isEmpty(applyInput.getMemberId())) {
                //直接通过手机号添加用户
                cmember = cmemberBizService.saveOrUpdateCmember(ApplyInput.transformMember(applyInput), partnerId);
            } else {
                //更新用户信息
                cmember = cmemberBizService.updateImportantInfo(ApplyInput.transformMember(applyInput), memberService.get(applyInput.getMemberId()));
            }

            //审核信息维护
            CMemberInfo cmemberInfo = cMemberInfoService.getByMemberId(cmember.getId());
            if (cmemberInfo == null) {
                cmemberInfo = new CMemberInfo();
                cmemberInfo.setMemberId(cmember.getId());
                cmemberInfo.setCheckStatus(CMemberInfo.CHECK_STATUS_ADOPT);
                cMemberInfoService.insert(cmemberInfo);
            }

            //机构用户关系维护
            PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(partnerId, cmember.getId());

            boolean hasZxgsPartner = memberMgmtService.hasZxgsPartner(partnerId, cmember.getId());

            if (null == partnerMember && !hasZxgsPartner) {
                partnerMember = new PartnerMember();
                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(cmember.getId());
                PartnerMember mainOrg = partnerMemberService.getMainOrg(cmember.getId(), partnerId);
                if (mainOrg == null) {
                    partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                    partnerMemberService.insert(partnerMember);
                }
                try {
                    if (mainOrg == null) {
                        //添加赠送积分
                        integralBizService.addGiftIntegral(partnerId, cmember.getId());
                    }
                } catch (Exception e) {
                    logger.error("添加赠送积分异常", e);
                }
            }

            integralBizToService.generateXZGSXCXQRCode(partnerId, cmember.getId());

            applyInput.setOrderType(OrderType.ORDER_ACTIVITY.getCode());
            ApplyOutput applyOutput = memberActBizService.getApplyData4(cmember.getId(), applyInput, project, counterfoil);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("活动报名异常", e);
            return AjaxResult.error(e.getMessage(), applyInput.getId());
        } catch (Exception e) {
            logger.error("活动报名异常", e);
            return AjaxResult.error(e.getMessage(), applyInput.getId());
        }
    }

    /**
     * 消息发送视图
     *
     * @param targetId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "integralMessageView")
    public ModelAndView integralMessageView(String targetId, String partnerId) {
        ModelAndView modelAndView = new ModelAndView("/activity/integralMessageView");
        TargetTemplate targetTemplate = null;

        Map<Integer, String> types = TargetTemplateType.convertMap(2);
        Map<String, Object> mmp = new HashMap<>();
        mmp.put("actId", targetId);
        for (Map.Entry<Integer, String> entry : types.entrySet()) {
            Integer signin;
            if (TargetTemplateType.INTEGRAL_STATUS_ALL.getCode().equals(entry.getKey())) {
                signin = null;
            } else {
                signin = 1;
            }
            mmp.put("signin", signin);
            Integer num = memberActService.memberActCount(mmp);
            entry.setValue(entry.getValue() + "(" + num + "人)");
        }
        PackageCount packageCount = packageCountService.getUnique(new PackageCount(memberGroupBizService.getXzgsMemberId(), TargetType.PUSH_SMS.getCode()));

        //积分类型
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        CIntegralType cIntegralType = new CIntegralType();
        if (currentUser.isChild()) {
            cIntegralType.setCreateBy(currentUser.getPartnerId());
        } else {
            cIntegralType.setCreateBy(currentUser.getId());
        }

        cIntegralType.setCategory(IntegralType.CINTEGRALTYPE_CATEGORY_ORDINARY.getCode());
        List<CIntegralType> list = integralTypeService.list(cIntegralType);
        modelAndView.addObject("partnerId", partnerId);
        modelAndView.addObject("activityId", targetId);
        modelAndView.addObject("types", list);
        modelAndView.addObject("packageCount", packageCount);
        modelAndView.addObject("mtypes", types);
        modelAndView.addObject("targetTemplate", targetTemplate);
        return modelAndView;
    }

    /**
     * 行知公社活动数据迁移到子账号下
     *
     * @author yifeng
     * @date 10:38 2019/11/12
     **/
    @ResponseBody
    @RequestMapping(value = "xzgsDataMigration")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult xzgsDataMigration() {
        try {
            String memberId = memberGroupBizService.getXzgsMemberId();
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_JX.getValue(), memberId, XzgsAccountEnum.XZGS_JX.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_QL.getValue(), memberId, XzgsAccountEnum.XZGS_QL.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_YJ.getValue(), memberId, XzgsAccountEnum.XZGS_YJ.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_ZX.getValue(), memberId, XzgsAccountEnum.XZGS_ZX.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_HP.getValue(), memberId, XzgsAccountEnum.XZGS_HP.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_ZY.getValue(), memberId, XzgsAccountEnum.XZGS_ZY.getKey());
            activityBizService.xzgsActivityDataMigration(XzgsAccountEnum.XZGS_KP.getValue(), memberId, XzgsAccountEnum.XZGS_KP.getKey());
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("活动数据迁移异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("活动数据迁移异常");
        }
    }

    @RequestMapping(value = "selectActivity")
    public ModelAndView selectActivity(ActivityWithMemberPartner activity, Page page) {
        ModelAndView mv = new ModelAndView("activity/selectActivity");
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(0);
        Map<String, Object> params = Maps.newHashMap();
        List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);
        mv.addObject("activities", activities);
        mv.addObject("page", page);
        mv.addObject("activity", activity);
        return mv;
    }
}
